<template>
  <div class="drugInformationManagement">
    <modules-title title-name="药品信息管理">
      <template slot="btn">
        <el-button class="border-btn" plain @click="exportDrug">导出</el-button>
        <!-- <el-upload
          class="importDataBtn"
          style="margin-left:10px"
          ref="excelFile"
          :limit="1"
          :auto-upload="false"
          accept=".xlsx"
          :action="UploadUrl()"
          :before-upload="beforeUploadFile"
          :on-change="fileChange"
          :on-success="handleSuccess"
          :on-error="handleError"
          :file-list="fileList"
        >
          <el-button class="border-btn" plain @click="importData"
            >导入</el-button
          >

        </el-upload> -->
        <el-button class="border-btn" plain @click="importData">导入</el-button>
        <el-button class="border-btn" plain @click="templateDrug"
        >下载模板
        </el-button
        >
        <el-button type="primary" class="main-btn" @click="newDrugs"
        >新增药品
        </el-button>
      </template>
    </modules-title>
    <div class="main">
      <div class="searchBar">
        <el-form inline>
          <el-form-item label="药品检索">
            <el-autocomplete
              :popper-append-to-body="false"
              clearable
              @focus="inputLenvo"
              @input="inputLenvo"
              @select="changeLenvo"
              class="inline-input"
              v-model="form.key"
              :fetch-suggestions="
                (queryString, cb) => {
                  querySearch(queryString, cb, 'product_name');
                }
              "
              @keyup.enter.native="getDrugsListData(form)"
              placeholder="名称/厂家/条码"
            ></el-autocomplete>
            <!--  <el-input
              @keyup.enter.native="getDrugsListData(form)"
              clearable
              class="inline-input"
              v-model="form.key"
              placeholder="名称/厂家/条码"
            ></el-input> -->
          </el-form-item>
          <el-form-item label="药品类型">
            <el-select
              @change="onChange1"
              v-model="form.category_id"
              placeholder="请选择药品类型"
            >
              <el-option
                v-for="item in optionsCategory"
                :key="item.ID"
                :label="item.category_name"
                :value="item.ID"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="药品状态">
            <el-select
              v-model="form.product_status"
              placeholder="请选择"
              @change="onChange"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="main-btn"
              @click="getDrugsListData(form)"
            >查询
            </el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="main-btn" @click="resetForm"
            >重置
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="table">
        <el-table
          :data="tableData"
          border
          :header-cell-style="{
            backgroundColor: '#F5F5F5',
            color: '#333333',
            fontFamily: 'MicrosoftYaHeiUI',
            fontSize: '14px',
            fontWeight: 900
          }"
        >
          <el-table-column
            prop="product_name"
            label="药品名称"
            align="center"
            min-width="8%"
          >
          </el-table-column>
          <el-table-column
            min-width="8%"
            prop="approval"
            label="批准文号"
            align="center"
          >
          </el-table-column>

          <el-table-column
            min-width="10%"
            prop="pack"
            label="规格包装"
            align="center"
          >
          </el-table-column>
          <el-table-column
            min-width="14%"
            prop="production"
            label="生产厂家"
            align="center"
          >
          </el-table-column>
          <el-table-column
            min-width="6%"
            prop="category_name"
            label="产品类型"
            align="center"
          >
          </el-table-column>
          <el-table-column
            min-width="8%"
            prop="buy_price"
            label="是否属于OTC"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.otc == true">
                是
              </div>
              <div v-else>否</div>
            </template>
          </el-table-column>
          <el-table-column
            min-width="9%"
            prop="bar_code"
            label="条形码"
            align="center"
          >
          </el-table-column>
          <el-table-column
            min-width="6%"
            prop="price"
            label="处方价"
            align="center"
          >
            <template slot-scope="scope">
              <div class="price">
                ￥{{ scope.row.price }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="number"
            label="总库存"
            align="center"
            min-width="6%"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.number }}{{ scope.row.piece_unit }}</div>
            </template>
          </el-table-column>
          <el-table-column label="是否启用" min-width="6%" align="center">
            <template slot-scope="scope">
              <div @click="changeState(scope.row)" class="enableDis">
                <el-switch
                  style="pointer-events: none;"
                  v-model="scope.row.product_status == 0 ? false : true"
                  active-color="#00A854"
                >
                </el-switch>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" min-width="7%">
            <template slot-scope="scope">
              <div class="btn-container">
                <el-button type="text" @click="editDrugs(scope.row.id)"
                >编辑
                </el-button
                >

                <span>|</span>
                <el-button
                  type="text"
                  class="red-text-btn"
                  @click="deleteDrugs(scope.row.id)"
                >删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="form.pager.number"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="form.pager.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
  import modulesTitle from "@/components/modulesTitle.vue";

  import {
    getDrugsList,
    deleteDrugsData,
    getDrugsCategory,
    exportTemplate,
    stateChange,
    exportDownload,
    exportImport,
    getCentralList
  } from "@/api/drugsManagement.js";

  export default {
    components: {modulesTitle},
    name: "drugInformationManagement",

    data() {
      return {
        inputAdv: [],
        fileList: [],
        total: 0,
        optionsCategory: [],
        form: {
          key: "",
          product_status: -1,
          category_id: 0,

          pager: {
            number: 1,
            size: 10
          }
        },

        value: "",
        input2: "",
        statusOptions: [
          {label: "全部", value: -1},
          {label: "启用", value: 1},
          {label: "停用", value: 0}
        ],

        tableData: [{product_status: 0}]
      };
    },
    created() {
      this.getDrugsCategoryData();
      this.$emit("getMessage", "drugInformationManagement");
      this.getDrugsListData(this.form);
    },
    methods: {
      onChange(val) {
        this.form.product_status = val
        this.form.pager.number = 1
        this.getDrugsListData(this.form);
      },
      onChange1(val) {
        this.form.category_id = val
        this.form.pager.number = 1
        this.getDrugsListData(this.form);
      },
      resetForm() {
        this.form = {
          key: "",
          product_status: -1,
          category_id: 0,
          pager: {
            number: 1,
            size: 10
          }
        }
        this.getDrugsListData(this.form);
      },
      inputLenvo() {
        if (this.form.key != "") {
          getCentralList({prefix: this.form.key, size: 10}).then(res => {
            console.log(res.data);
            this.inputAdv = [];
            if (
              res.code == 200 &&
              res.data.self == true &&
              res.data.ElasticProduct != []
            ) {
              this.inputAdv = res.data.ElasticProduct;
              this.inputAdv.forEach(item => {
                item.value = item.product_name;
              });
            }
          });
        }
      },
      querySearch(queryString, cb, val) {
        let restaurants = this.inputAdv;
        console.log(restaurants);

        var results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;

        //   var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        console.log("22222222");
        console.log(results);
        if (results != []) {
          results = this.filterData(results);
        }

        cb(results);
      },
      filterData(arr) {
        let newArr = [];
        let bool = true;
        arr.forEach(item => {
          bool = true;
          if (newArr != []) {
            newArr.every(itm => {
              if (itm.product_name == item.product_name) {
                bool = false;
              }
              return itm.product_name != item.product_name;
            });
            if (bool == true) {
              newArr.push(item);
            }
          } else {
            newArr.push(item);
          }
        });
        console.log(newArr);

        return newArr;
      },

      createFilter(queryString) {
        return restaurant => {
          // return 1;
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0 ||
            restaurant.name_pinyin
              .toLowerCase()
              .indexOf(queryString.toLowerCase()) === 0
          );
        };
      },
      handleSizeChange(val) {
        this.form.pager.size = val;
        this.getDrugsListData(this.form);
      },
      handleCurrentChange(val) {
        this.form.pager.number = val;
        this.getDrugsListData(this.form);
      },
      getDrugsCategoryData() {
        getDrugsCategory().then(res => {
          this.optionsCategory = res.data;
        });
      },
      editDrugs(id) {
        /* this.$router.push({
              name: 'newDrugs',
              params: {
                  id: id
              }
          }) */
        this.$router.push({
          path: "/drugsManagement/newDrugs",
          query: {
            id: id
          }
        });
      },
      async deleteDrugs(id) {
        const confirm = await this.$confirm("确认删除该药品吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).catch(err => err);

        if (confirm !== "confirm") {
          return this.$message.info("已取消");
        } else {
          deleteDrugsData({product_id: id}).then(res => {
            if (res.code == 200) {
              if (this.tableData.length == 1 && this.form.pager.number > 1) {
                this.form.pager.number--;
              }
              this.getDrugsListData(this.form);
            } else {
              this.$message.error("删除失败");
            }
          });
        }
      },
      getDrugsListData(data) {
        getDrugsList(data).then(res => {
          this.tableData = [];
          this.tableData = res.data.data;
          this.total = res.data.total;
        });
      },
      // 新增药品按钮
      newDrugs() {
        this.$router.push({name: "newDrugs"});
      },
      //启用停用
      async changeState(row) {
        let tip = "";
        if (row.product_status == 0) {
          tip = "确认启用该药品吗";
        } else {
          tip = "确认停用该药品吗";
        }

        const confirm = await this.$confirm(tip, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).catch(err => err);

        if (confirm !== "confirm") {
          return this.$message.info("已取消");
        }
        stateChange({product_id: row.id}).then(res => {
          if (res.code == 200) {
            this.getDrugsListData(this.form);
          } else {
            this.$message.error("修改失败");
          }
        });
      },
      //导出
      async exportDrug() {
        const res = await exportDownload();
        const link = document.createElement("a");
        let blob = new Blob([res], {
          type:
            "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        console.log(sessionStorage.getItem("Content-Disposition"));
        link.download = "药品信息管理列表.xlsx";

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
      changeLenvo() {
        this.getDrugsListData(this.form);
      },

      // 文件上传成功
      handleSuccess(res, file, fileList) {
        this.$message.success("文件上传成功");
      },
      // 文件状态改变时的钩子
      fileChange(file, fileList) {
        console.log("raw");
        console.log(file.raw);
        this.fileList.push(file.raw);
        console.log(this.fileList);
      },
      // 文件上传失败
      handleError(err, file, fileList) {
        this.$message.error("文件上传失败");
      },
      UploadUrl: function () {
        // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
        return "";
      },
      beforeUploadFile(file) {
        console.log("before upload");
        console.log(file);
        let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
        let size = file.size / 1024 / 1024;
        if (extension !== "xlsx") {
          this.$message.warning("只能上传后缀是.xlsx的文件");
        }
        if (size > 10) {
          this.$message.warning("文件大小不得超过10M");
        }
      },
      //导入
      async importData() {
        return this.$message("暂不可用");
        const res = await exportImport();
      },

      //下载模板
      async templateDrug() {
        const res = await exportTemplate();
        const link = document.createElement("a");
        let blob = new Blob([res], {
          type:
            "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = "药品信息管理模板.xlsx";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  };
</script>
<style lang="scss" scoped>
  @import "@/assets/scss/drugsManagement/drugInformationManagement.scss";
</style>
